package net.mihome.app.ui;

import java.util.ArrayList;
import java.util.List;

import net.mihome.app.AppContext;
import net.mihome.app.AppException;
import net.mihome.app.adapter.RssNewsAdapter;
import net.mihome.app.bean.RssNews;
import net.mihome.app.bean.RssResource;
import net.mihome.app.common.UIHelper;
import net.mihome.app.widget.PullToRefreshListView;
import net.mihome.app.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

public class RssNewsListActivity extends Activity {
	private String rssResource;
	private PullToRefreshListView newsListView;
	private List<RssNews> list=new ArrayList<RssNews>();
	private RssNewsAdapter rssNewsAdapter;
	private View progressView;
	private AppContext appContext;// 全局Context
	private Handler handler;
	private View homeView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rss_list_news);
		rssResource=getIntent().getStringExtra("rssResource");
		initView();
		initData();
	}
	/**
	 * 初始化页面元素
	 * */
	public void initView(){
		appContext = (AppContext) getApplication();
		newsListView=(net.mihome.app.widget.PullToRefreshListView) findViewById(R.id.rss_list_news_lv);
		newsListView.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
			@Override
			public void onRefresh() {
				initData();
			}
		});
		homeView=findViewById(R.id.news_detail_home);
		progressView=findViewById(R.id.news_detail_head_progress);
		homeView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				UIHelper.showHome(RssNewsListActivity.this);
			}
		});
		rssNewsAdapter=new RssNewsAdapter(RssNewsListActivity.this,list);
		newsListView.setAdapter(rssNewsAdapter);
		handler=new Handler(new Handler.Callback() {
			@Override
			public boolean handleMessage(Message arg0) {
				// TODO Auto-generated method stub
				rssNewsAdapter=new RssNewsAdapter(RssNewsListActivity.this,list);
				newsListView.setAdapter(rssNewsAdapter);
				rssNewsAdapter.notifyDataSetChanged();
				progressView.setVisibility(View.GONE);
				newsListView.onRefreshComplete();
				return false;
			}
		});
	}
	/***
	 * 线程获取数据
	 **/
	public void initData(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				Message message=new Message();
				try{
					RssResource resource=new RssResource();
					resource.setHref(rssResource);
					list=appContext.getRssNewsList(resource, 0, 20);
					message.what=1;
				}catch(AppException e){
					message.what=0;
				}
				handler.sendMessage(message);
			}
		}).start();
	}
}
